﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Crank.Core
{
    public class AutoKeyModelTransformer : IModelTransformer
    {
        private bool HasKey(EntityDef entity)
        {
            foreach (AttributeDef att in entity.Attributes)
                if (att.IsKey)
                    return true;
            return false;
        }

        private void AddKey(EntityDef entity)
        {
            AttributeDef att = new AttributeDef("_ID");
            att.IsKey = true;
            att.IsAuto = true;
            att.IsRequired = true;
            att.Type = "INT";
            entity.Attributes.Add(att);
        }

        #region IModelTransformer Members

        public void ApplyTransform(DataModel target)
        {
            var EntitiesToCheck = new List<EntityDef>();
            foreach (EntityDef entity in target.Entities.Values)
                if (!HasKey(entity))
                    EntitiesToCheck.Add(entity);
            foreach (LinkDef link in target.Links)
                if (link.Detail.IsKey)
                    EntitiesToCheck.Remove(link.LHS);

            EntitiesToCheck.ForEach(AddKey);
        }

        #endregion
    }
}
